package com.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shop.config.RabbitMqConfig;
import com.shop.domain.Order;

import com.shop.domain.ProductDetails;
import com.shop.domain.Task;
import com.shop.feign.CartFeign;

import com.shop.feign.GoodsFeign;
import com.shop.mapper.TaskMapper;
import com.shop.service.OrderService;
import com.shop.mapper.OrderMapper;
import com.shop.util.TokenDecode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* @author 靳润波
* @description 针对表【itbuka_order】的数据库操作Service实现
* @createDate 2024-09-02 09:26:08
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private CartFeign cartFeign;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TokenDecode tokenDecode;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public List<Order> selectAll() {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getIsDelete,0);
        return orderMapper.selectList(wrapper);
    }

    @Override
    public List<Order> selectList(Order order) {
        LambdaQueryWrapper<Order> wrapper = this.lqw(order);
        return orderMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public Integer insert(Order order) {
        //查库存够不够
        ProductDetails productDetails = new ProductDetails();
        productDetails.setId(order.getProductId());
        ProductDetails details = goodsFeign.select(productDetails).getData().get(0);
        if(details.getInventory()<=0){
            // 库存inventory 不足
            return -1;
        }
        Date date = new Date();
        //下单
        order.setId(IdWorker.getId());
        order.setCreateTime(date);
        String userName = tokenDecode.getUserInfo().get("user_name");
        order.setBuyerName(userName);
        int insert = orderMapper.insert(order);
        if(insert != 1){
            return -2;
        }

        // 发送消息到task
        Task task = new Task();
        task.setId(IdWorker.getId());
        task.setTaskType("0");
        task.setMqExchange(RabbitMqConfig.ORDER_EXCHANGE);
        task.setMqRoutingkey(RabbitMqConfig.ORDER_QUEUE);
        task.setRequestBody(JSONObject.toJSONString(order));
        taskMapper.insert(task);

        // 删除购物车中的商品
        cartFeign.delete(order.getProductId().toString());

        rabbitTemplate.convertAndSend(RabbitMqConfig.ORDER_EXCHANGE,RabbitMqConfig.ORDER_QUEUE, JSON.toJSONString(task));

        // 发消息给死信队列
        rabbitTemplate.convertAndSend("",RabbitMqConfig.PAY_QUEUE,JSON.toJSONString(order));

        return 1;
    }

    @Override
    public Integer delete(String ids) {
        try {
            String[] split = ids.split(",");
            for (String id : split) {
                Order iOrder = new Order();
                iOrder.setId(Long.parseLong(id));
                iOrder.setIsDelete(1);
                orderMapper.updateById(iOrder);
            }
            return 1;
        }catch (Exception e){
            return -1;
        }
    }

    @Override
    public Integer update(Order order) {
        return orderMapper.updateById(order);
    }

    @Override
    public Page<Order> pageAll(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        return (Page<Order>) this.selectAll();
    }

    @Override
    public Page<Order> pageList(Order order, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        return (Page<Order>) this.selectList(order);
    }

    @Override
    public void batchSend(List<Order> orders) {
        for (Order order : orders) {
            if(order.getId()==null){
                throw new RuntimeException("订单号为空");
            }
            if(order.getShippingMethod()==null || order.getTrackingNumber()==null){
                throw new RuntimeException("请选择快递公司和填写快递单号");
            }
            //进行状态校验
            Order order1 = orderMapper.selectById(order.getId());
            if (order1.getStatus() != 2){
                throw new RuntimeException("订单状态不是待发货");
            }
            Order orderSelect = orderMapper.selectById(order.getId());
            orderSelect.setStatus(3);
            orderSelect.setUpdateTime(new Date());
            orderSelect.setShippingMethod(order.getShippingMethod());
            orderSelect.setTrackingNumber(order.getTrackingNumber());
            orderMapper.updateById(orderSelect);
        }
        // 发送延迟消息 监听是否确认收货
        rabbitTemplate.convertAndSend("",RabbitMqConfig.RECEIVING_QUEUE,JSON.toJSONString(orders));
    }

    @Override
    public void confirmTask(String orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }if(order.getStatus() !=3){
            throw new RuntimeException("订单状态异常");
        }
        order.setStatus(6);
        order.setUpdateTime(new Date());
        orderMapper.updateById(order);
    }


    public LambdaQueryWrapper lqw(Order iOrder){
        LambdaQueryWrapper <Order> lqw = new LambdaQueryWrapper<>();
        if (iOrder.getId() != null){
            lqw.eq(Order::getId,iOrder.getId());
        }
        if (iOrder.getSource() != null){
            lqw.eq(Order::getSource,iOrder.getSource());
        }
        if (iOrder.getType() != null){
            lqw.eq(Order::getType,iOrder.getType());
        }
        if (iOrder.getBuyerName() != null){
            lqw.eq(Order::getBuyerName,iOrder.getBuyerName());
        }
        if (iOrder.getMoney() != null){
            lqw.eq(Order::getMoney,iOrder.getMoney());
        }
        if (iOrder.getStatus() != null){
            lqw.eq(Order::getStatus,iOrder.getStatus());
        }
        if (iOrder.getUpdateTime() != null){
            lqw.eq(Order::getUpdateTime,iOrder.getUpdateTime());
        }
        if (iOrder.getCreateTime() != null){
            lqw.eq(Order::getCreateTime,iOrder.getCreateTime());
        }
        if (iOrder.getIsDelete() != null){
            lqw.eq(Order::getIsDelete,iOrder.getIsDelete());
        }
        if (iOrder.getAddressId() != null){
            lqw.eq(Order::getAddressId,iOrder.getAddressId());
        }
        if (iOrder.getProductId() != null){
            lqw.eq(Order::getProductId,iOrder.getProductId());
        }
        if (iOrder.getNum() != null){
            lqw.eq(Order::getNum,iOrder.getNum());
        }
        if (iOrder.getTradeNo() != null){
            lqw.eq(Order::getTradeNo,iOrder.getTradeNo());
        }
        return lqw;
    }
}




